<?php
/**
 * Created by PhpStorm.
 * User: cheng
 * Date: 2017/2/16
 * Time: 9:58
 */
 require_once("config.php");
 require_once("json.php");
 class UserInfo{
     public function __call($name,$arguments){
         $json = new CreateJson();
         $json->response(300,"没有这个".$name."方法哦!","") ;
     }
     public function getShopId(){
         $table = 'vote_user';
         //$pdoMySQL = new PdoMySQL();
         //$res = $pdoMySQL::find($table,"company_name ='".ACTIVE_COMPANY."'",'id');
         $sql = "SELECT id FROM ".$table." WHERE company_name='".ACTIVE_COMPANY."'";
         $stmt = $GLOBALS['PDO']->prepare($sql);
         $stmt->execute();
         $res=$stmt->fetch();
         //获取活动的id
         $id = $res['id'];
         $idArr = array(
             "companyId" => $id
         );
         echo json_encode($idArr);
     }
     public function getAccessTicket(){
         $ticket_url = "http://auth.bbpaina.com/wechat/oauth.php?wx=aoershi&url=".urlencode("http://ceshi.babypn.com/user_register.php?action=acceptAccess");
         header("Location:".$ticket_url);
     }
     public function acceptTicket(){
         $ticket = $_GET['access_ticket'];
         $_SESSION['ticket'] = $ticket;
         $res = file_get_contents('http://auth.bbpaina.com/wechat/get.php?ver=0.1&ticket=' . $ticket);
         $openidJson = json_decode($res, true);
         if ($openidJson['status'] == 'ok') {
             $_SESSION['openid'] = $openidJson['result']['open_id'];
             $_SESSION['access_token'] = $openidJson['result']['access_token'];
         }
         $webUrl = "http://ceshi.babypn.com/ticket/index.html";
         header("Location:".$webUrl);
     }
     public function getUserInfo() {
        $baby_Name   =   isset($_GET['baby_name'])?$_GET['baby_name']:null;
        $baby_sex    =   isset($_GET['baby_sex'])?$_GET['baby_sex']:null;
        $baby_birth  =   isset($_GET['baby_birth'])?$_GET['baby_birth']:null;
        $user_name   =   isset($_GET['user_name'])?$_GET['user_name']:null;
        $user_mobile =   isset($_GET['user_mobile'])?$_GET['user_mobile']:null;
        $user_addr   =   isset($_GET['user_addr'])?$_GET['user_addr']:null;
        $companyId   =   isset($_GET['companyId'])?$_GET['companyId']:null;
        //$latitude   =   isset($_GET['latitude'])?$_GET['latitude']:null;
        //$longitude   =   isset($_GET['longitude'])?$_GET['longitude']:null;
        $json = new CreateJson();
        if(is_null($baby_Name)||empty($baby_Name)){
            $json->response(400,"没有小孩姓名","");
        }
        if(is_null($baby_sex)||empty($baby_sex)){
             $json->response(400,"没有小孩性别","");
         }
         if(is_null($baby_birth)||empty($baby_birth)){
             $json->response(400,"没有小孩生日","");
         }
         if(is_null($user_name)||empty($user_name)){
             $json->response(400,"没有用户名","");
         }
         if(is_null($user_mobile)||empty($user_mobile)){
             $json->response(400,"没有手机号码","");
         }
         if(is_null($user_addr)||empty($user_addr)){
             $json->response(400,"没有用户地址","");
         }
         if(is_null($companyId)||empty($companyId)){
             $json->response(400,"没有shopId","");
         }
         if (!(($_FILES["user_img"]["type"] == "image/gif")
             || ($_FILES["user_img"]["type"] == "image/jpg")
             || ($_FILES["user_img"]["type"] == "image/png")
             || ($_FILES["user_img"]["type"] == "image/jpeg")
             || ($_FILES["user_img"]["type"] == "image/pjpeg")))
         {
             $json->response(400,"文件格式不正确","");
         }
         if(empty($_FILES["user_img"]["tmp_name"])){
             $json->response(400,"图片不能为空","");
         }
         //5M
       if($_FILES["user_img"]["size"] > 5242880){
             $json->response(400,"文件大小不能超出5M","");
         }
       move_uploaded_file($_FILES["user_img"]["tmp_name"],
             "uploads/" . $_SESSION['ticket'].$_FILES["user_img"]["name"]);
        $user_table = 'vote_company';
        $resArr = array(
           ":babyname"        =>   $baby_Name,
           ":username"        =>   $user_name,
           ":babysex"         =>   $baby_sex,
           ":babybirth"       =>   $baby_birth,
           ":usermobile"      =>   $user_mobile,
           ":useraddr"        =>   $user_addr,
           ":status"          =>   1,
           ":userimg"         =>   "../uploads/".$_SESSION['ticket'].$_FILES["user_img"]["name"],
           ":activeid"        =>   $companyId,
           ":useropenid"      =>   $_SESSION['openid'],
           ":userip"          =>   $_SERVER['REMOTE_ADDR'],
           ":createtime"      =>   time(),
           ":useraccesstoken" => $_SESSION['ticket']
        );
// 域名绑定问题，暂停
/*        $locationArr = array(
            ":latitude "        =>    $latitude,
            ":longitude "       =>    $longitude,
            ":useropenid"       =>    $_SESSION['openid'],
            ":activeid"         =>    $companyId,
        );
        $sqlLocation = "INSERT INTO vote_location(`jingdu`,`weidu`,`user_openid`,`active_id`)VALUES(:latitude,:longitude,:useropenid,:activeid)";
        $st = $GLOBALS['PDO']->prepare($sqlLocation);
        $st->execute($locationArr);*/


        //$pdoMySQL = new PdoMySQL();
        //$result = $pdoMySQL::add($resArr,$user_table);
        //$user_id = $pdoMySQL::$lastInsertId;
        $sql = "INSERT INTO ".$user_table."(`baby_name`, `user_name`,`baby_sex`,`baby_birth`,`user_mobile`,`user_addr`,`status`,`user_img`,`active_id`,`user_openid`,`user_ip`,`create_time`,`user_access_token`)VALUES(:babyname,:username,:babysex,:babybirth,:usermobile,:useraddr,:status,:userimg,:activeid,:useropenid,:userip,:createtime,:useraccesstoken)";
        $stmt = $GLOBALS['PDO']->prepare($sql);
        $result = $stmt->execute($resArr);
        $user_id = $GLOBALS['PDO']->lastInsertId();
        $userIdArr =array(
            "userId" => $user_id
        );
        if($result){
            $json->response(200,"提交成功",$userIdArr);
        }else{
            $json->response(404,"提交失败","");
        }
     }
     public function getData(){
         $json = new CreateJson();
         $appId = "wxc3ea1e4d35e71db1";
         $timestamp = time();
         $nonceStr = $this->getString();
         if(empty($nonceStr) || is_null($nonceStr)){
             $json->response(400,"随机数丢失","");
         }
         $url = "http://ceshi.babypn.com/ticket/index.html";
         $ticket = $this->getTicket();
         if(empty($ticket) || is_null($ticket)){
             $json->response(400,"ticket丢失","");
         }
         $signature = "jsapi_ticket=".$ticket."&noncestr=".$nonceStr."&timestamp=".$timestamp."&url=".$url;
         $signature=sha1($signature);
         $dataArr = array(
             "appId"     => $appId,
             "timestamp" => $timestamp,
             "nonceStr"  => $nonceStr,
             "signature" => $signature
         );
         $json->response(200,"返回成功",$dataArr);
     }
     private function httpGet($url) {
         $curl = curl_init();
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($curl, CURLOPT_TIMEOUT, 500);
         // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
         // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
         curl_setopt($curl, CURLOPT_URL, $url);
         $res = curl_exec($curl);
         curl_close($curl);
         return $res;
     }
     public function getTicket(){
         if($_SESSION['ticket_time']>time() && $_SESSION["ticket"]){
             $ticket = $_SESSION["jsapi_ticket"];
         }else{
             $token = $_SESSION['access_token'];
             $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$token;
             $res = json_decode($this->httpGet($url));
             $ticket = $res->ticket;
             $_SESSION["jsapi_ticket"] = $ticket;
             $_SESSION['ticket_time'] = time()+7000;
         }
         return $ticket;
     }
     public function getString($len = 16){
         $arr = array(
             "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
             "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
             "0","1","2","3","4","5","6","7","8","9"
         );
         $str = "";
         $num = count($arr);
         for($i = 0; $i <= $len;$i++){
             $str.=$arr[rand(0,$num-1)];
         }
         return $str;
     }
 }